package com.wing.order.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.Result;
import com.wing.order.model.entity.DistributionDemand;
import com.wing.order.model.request.DistributionDemandDetailForm;
import com.wing.order.model.request.DistributionDemandForm;
import com.wing.order.service.DistributionDemandService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static java.lang.System.out;

/**
 * @author
 */
@Validated
@Api(value = "Admin-配货需求订单表管理", tags = "#/order/distributionDemand")
@RestController("distributionDemandController")
@RequestMapping("order/admin/distributionDemand")
@RequiredArgsConstructor
@Slf4j
public class DistributionDemandController {

    private final DistributionDemandService distributionDemandService;


    @Value("${platform.gatewayUrl}")
    private String gatewayUrl;


    @ApiOperation(value = "查询所有配货需求订单表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "status", value = "状态", defaultValue = "status", example = "status", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "distCode", value = "配货订单编号", defaultValue = "distCode", example = "distCode", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "creator", value = "创建人", defaultValue = "creator", example = "creator", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<DistributionDemand> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order

    ) {

        Page<DistributionDemand> pg = new Page<>(page, limit);
        QueryWrapper<DistributionDemand> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索

        IPage<DistributionDemand> list = distributionDemandService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加配货需求订单表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody DistributionDemandForm distributionDemandForm) throws Exception {

        if (distributionDemandService.add(distributionDemandForm) > 0) {
            //同步到平台端(请求路径还需配置)
            final String reqUri = gatewayUrl+"platformCab/order/admin/distributionDemand/addOrder";
            String jsonObject = JSONUtil.toJsonStr(distributionDemandForm);
            String tokenJson = HttpHelper.httpPost(reqUri, jsonObject);
            out.println(String.format("==========================>this is response:{%s}", tokenJson));
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "批量添加配货需求订单表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addList")
    public JsonResult addList(@RequestBody List<DistributionDemandDetailForm> distributionDemandDetailForms){
        try {//配需求计划同步过来多条数据汇总成一条订单 多条订单明细
            distributionDemandService.addList(distributionDemandDetailForms);
            return JsonResult.success(Result.Code.SUCCESS);
        } catch (Exception e) {
            log.error("addList fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "修改配货需求订单表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(DistributionDemandForm.Update.class) DistributionDemandForm distributionDemandForm) {
        DistributionDemand distributionDemand = distributionDemandService.getById(distributionDemandForm.getId());
        if (distributionDemand == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(DistributionDemand.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(distributionDemandForm, distributionDemand, copyOptions);
        if (distributionDemandService.updateById(distributionDemand)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除配货需求订单表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "distributionDemandId", value = "配货需求订单表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long distributionDemandId) {
        if (distributionDemandService.removeById(distributionDemandId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
}
